package com.draven.mall.service.impl;

import com.draven.mall.dispatch.*;
import com.draven.mall.entity.DispatchConfig;
import com.draven.mall.entity.Order;
import com.draven.mall.entity.Rider;
import com.draven.mall.service.DispatchConfigService;
import com.draven.mall.service.DispatchService;
import com.draven.mall.service.OrderService;
import com.draven.mall.service.RiderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 调度服务实现类
 */
@Service
public class DispatchServiceImpl implements DispatchService {

    private static final Logger log = LoggerFactory.getLogger(DispatchServiceImpl.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private RiderService riderService;

    @Autowired
    private DispatchConfigService dispatchConfigService;

    @Autowired
    private RandomDispatchAlgorithm randomAlgorithm;

    @Autowired
    private NearestRiderDispatchAlgorithm nearestRiderAlgorithm;

    @Autowired
    private HighestRatingDispatchAlgorithm highestRatingAlgorithm;

    @Autowired
    private LeastOrdersDispatchAlgorithm leastOrdersAlgorithm;

    @Autowired
    private CompositeDispatchAlgorithm compositeAlgorithm;

    // 算法映射表
    private final Map<Integer, DispatchAlgorithm> algorithms = new HashMap<>();

    /**
     * 在构造后初始化算法映射
     */
    @Autowired
    public void init() {
        algorithms.put(1, randomAlgorithm);
        algorithms.put(2, nearestRiderAlgorithm);
        algorithms.put(3, highestRatingAlgorithm);
        algorithms.put(4, leastOrdersAlgorithm);
        algorithms.put(5, compositeAlgorithm);
        
        log.info("调度算法初始化完成，共注册{}种算法", algorithms.size());
    }

    @Override
    public Long assignRider(Long orderId) {
        log.info("开始为订单 {} 分配骑手", orderId);
        
        try {
            // 获取订单信息
            Order order = orderService.getOrderById(orderId);
            if (order == null) {
                log.error("订单 {} 不存在", orderId);
                return null;
            }
            
            // 检查订单状态
            if (order.getStatus() != 1) { // 假设状态1为待接单
                log.error("订单 {} 状态不是待接单，无法分配骑手", orderId);
                return null;
            }
            
            // 为订单分配骑手
            Rider assignedRider = assignRiderForOrder(order);
            if (assignedRider == null) {
                log.error("没有合适的骑手可分配给订单 {}", orderId);
                return null;
            }
            
            // 更新订单的骑手ID
            boolean success = orderService.updateOrderRider(orderId, assignedRider.getId());
            if (!success) {
                log.error("更新订单 {} 的骑手信息失败", orderId);
                return null;
            }
            
            log.info("订单 {} 成功分配给骑手 {}", orderId, assignedRider.getId());
            return assignedRider.getId();
        } catch (Exception e) {
            log.error("为订单 {} 分配骑手时发生异常", orderId, e);
            return null;
        }
    }

    @Override
    public Rider assignRiderForOrder(Order order) {
        if (order == null) {
            log.error("订单为空，无法分配骑手");
            return null;
        }
        
        try {
            // 获取当前激活的调度配置
            DispatchConfig config = dispatchConfigService.getActiveConfig();
            if (config == null) {
                log.warn("没有激活的调度配置，使用默认随机分配算法");
                return assignRiderWithAlgorithm(order, 1); // 默认使用随机分配
            }
            
            log.info("使用算法类型 {} 为订单分配骑手", config.getAlgorithmType());
            return assignRiderWithAlgorithm(order, config.getAlgorithmType());
        } catch (Exception e) {
            log.error("获取激活的调度配置时发生异常，使用默认随机分配算法", e);
            return assignRiderWithAlgorithm(order, 1); // 出错时使用随机分配
        }
    }

    @Override
    public Rider assignRiderWithAlgorithm(Order order, int algorithmType) {
        if (order == null) {
            log.error("订单为空，无法分配骑手");
            return null;
        }
        
        try {
            // 获取所有可用的骑手
            List<Rider> availableRiders = riderService.getAvailableRiders();
            if (availableRiders == null || availableRiders.isEmpty()) {
                log.error("没有可用的骑手");
                return null;
            }
            
            // 获取对应的算法
            DispatchAlgorithm algorithm = algorithms.getOrDefault(algorithmType, randomAlgorithm);
            log.info("使用{}算法为订单分配骑手", algorithm.getName());
            
            // 使用算法分配骑手
            Rider assignedRider = algorithm.assignRider(order, availableRiders);
            
            if (assignedRider != null) {
                log.info("成功为订单 {} 分配骑手 {}", order.getId(), assignedRider.getId());
            } else {
                log.error("算法 {} 未能找到合适的骑手", algorithm.getName());
            }
            
            return assignedRider;
        } catch (Exception e) {
            log.error("使用算法分配骑手时发生异常", e);
            return null;
        }
    }
} 